package com.itheima.service.impl;

import com.itheima.exception.BusinessException;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.entity.Dept;
import com.itheima.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author zzw
 * @date 2025/4/23
 * @description 部门业务层实现类
 */
@Slf4j
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    /**
     * 保存部门
     *
     * @param dept 部门
     */
    @Override
    public void save(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.save(dept);
    }

    /**
     * 删除部门
     *
     * @param id 部门id
     */
    @Override
    public void delete(Integer id) {
        // 检查部门下是否有员工
        if (empMapper.countByDeptId(id) > 0) {
            // 如果部门下有员工，抛出业务异常
            throw new BusinessException("当前部门下有员工, 不能删除");
        }

        // 2.如果部门下没有员工，执行删除操作
        deptMapper.delete(id);
    }

    /**
     * 更新部门
     *
     * @param dept 部门
     */
    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }


    /**
     * 根据id查询部门
     *
     * @param id 部门id
     * @return Dept 部门
     */
    @Override
    public Dept getById(Integer id) {
        return deptMapper.getById(id);
    }


}
